package de.baumann.browser.utils

import android.annotation.SuppressLint
import android.os.CountDownTimer
import android.widget.TextView
import java.text.ParseException

class CountTimer3(
        var textView: TextView,
        var entTime: Long,
        var endTimeCallback: EndTimeCallback? = null
) : CountDownTimer(Long.MAX_VALUE, 1000) {

    override fun onFinish() {
    }

    @SuppressLint("SetTextI18n")
    override fun onTick(millisUntilFinished: Long) {
        dateDiff(System.currentTimeMillis(), entTime * 1000)
    }

    @SuppressLint("SetTextI18n")
    fun dateDiff(startTime: Long, endTime: Long) {
        val nd = 1000 * 24 * 60 * 60.toLong() //一天的毫秒数
        val nh = 1000 * 60 * 60.toLong() //一小时的毫秒数
        val nm = 1000 * 60.toLong() //一分钟的毫秒数
        val ns: Long = 1000 //一秒钟的毫秒数long diff;try {
        //获得两个时间的毫秒时间差异
//        long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        val diff = endTime - startTime
        val hour = diff % nd / nh //计算相差剩余多少小时
        val hour2 = diff / nh //计算相差多少小时
        val min = diff % nd % nh / nm //计算差多少分钟
        val sec = diff % nd % nh % nm / ns //计算差多少秒//输出结果

        if (min <= 0 && sec <= 0) {
            textView.text = "00:00"
            endTimeCallback?.callback()
            return
        }

        val mins = if (min < 10) {
            "0${min}"
        } else {
            "$min"
        }

        val secs = if (sec < 10) {
            "0${sec}"
        } else {
            "$sec"
        }
        textView.text = "${mins}:${secs}"
    }
}

interface EndTimeCallback {
    fun callback()
}